package cloud.zt.springboot.utils;


import cloud.zt.springboot.constant.Constants;

import javax.servlet.http.HttpServletRequest;

/**
 * @author RedReins
 * @version 1.0
 * @description: TODO
 * @date 2021/9/6 21:29
 */

public class TokenUtils {


    /**
     * 获取用户
     */
    public static String getUsername()
    {
        String username = ServletUtils.getRequest().getHeader(Constants.DETAILS_USERNAME);
        return ServletUtils.urlDecode(username);
    }

    /**
     * 获取请求token
     *
     */
    public static String getToken()
    {
        return getToken(ServletUtils.getRequest());
    }

    /**
     * 根据request获取请求token
     */
    public static String getToken(HttpServletRequest request)
    {
        String token = request.getHeader(Constants.TOKEN_AUTHENTICATION);
        return replaceTokenPrefix(token);
    }

    /**
     * 替换token前缀
     */
    public static String replaceTokenPrefix(String token)
    {
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX))
        {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

}
